package com.shuimin.as;

import com.shuimin.as.model.repair.*;
import com.shuimin.as.service.excel.ImportService;
import pond.common.S;
import pond.db.sql.Criterion;
import pond.web.Request;
import pond.web.restful.API;

import java.io.IOException;
import java.util.List;

/**
 * Created by sky on 2017/7/21.
 */
public class EXCEL extends API {
    {
        post("/import",(req,resp)->{

            String shop_id=req.param("shop_id");
            AsShopExtra extra=App.DB.get(t -> {
                List<AsShopExtra> list = t.recordsQuery(AsShopExtra.class, "shop_id", Criterion.EQ, shop_id);
                if (list.size() > 0) {
                    return list.get(0);
                } else return null;
            });
            if(extra==null) resp.send(400);
            Request.UploadFile uf = req.file("repair_order");

            try {
                S._for(ImportService.importExcel(extra,uf.inputStream())).each(item -> {
                    App.DB.post(t -> {
                        if(item==null) return ;
                        //通过sn查询系统中是否已经存在
                        List list = t.recordsQuery(AsRepairOrder.class, "sn", Criterion.EQ, item.get("sn"));

                        if (list.size() <= 0) {
                            S.echo(S.dump(item));
                            AsCustomer customer = item.customer();
                            AsVehicle vehicle = item.vehicle();
                            AsReceipt receipt = item.receipt();
                            AsRepairOrder order = item.order();
                            t.recordInsert(order);
                            t.recordInsert(customer);
                            t.recordInsert(vehicle);
                            t.recordInsert(receipt);

                        }
                    });
                });
                resp.send(200);
            } catch (IOException e) {
                e.printStackTrace(resp.writer());
                resp.send(500);
            }


        });
    }
}
